<template>
    <div class="ReportVideo_div">
        <a-row id="ReportVideo_row1" class="ReportImage_row1">
            <a-col :span="24" class="ReportImage_col">
                <el-button type="info" v-on:click="chooseVideo()" id="ReportVideo_btn1"  class="ReportImage_btn1" clickMusic="true">
                    本地选择
                </el-button>
            </a-col>
        </a-row>

        <a-row id="ReportImage_row2" class="ReportImage_row1">
            <a-col :span="24" class="ReportImage_col">
                <!--getVideo()大文件视频3gp格式上传-->
                <el-button type="info" v-on:click="getVideo()" id="ReportVideo_btn"  class="ReportImage_btn1" clickMusic="true">
                    录制视频
                </el-button>
            </a-col>
        </a-row>

        <a-row>
            <a-col :span="24" class="showTextCol">
                <div class="showTextOkDiv" v-if="isOk==='1'">{{myFileName}}<br/>上传视频成功</div>
                <div class="showTextFailDiv" v-if="isOk==='0'">{{myFileName}}<br/>上传数据失败</div>
            </a-col>
        </a-row>
        <div class="showBox" v-if="Loading" >
            <div class="loading"></div>
            <div class="progress_div">{{progress}}</div>
        </div>
    </div>
</template>
<style>

    .progress_div{
        font-size: 6vw;
        color: black;
        text-align: center;
        margin-top: 1.5vw;
    }

    @keyframes loading {
        0% {
            transform: rotate(0deg);
        }
        100% {
            transform: rotate(360deg);
        }
    }
    .showBox{
        padding: 45vh 0 0 0 ;
        width: 100vw;
        height: 100vh;
        background: rgba(0,0,0,0.5);
        z-index: 100;
        top: 0;
        left: 0;
        position: absolute;
    }
    .ReportVideo_div{
        background: rgba(237,237,237,0.3);
        min-height: 100vh;
        width: 100vw;
        padding-top: 5vw;
    }
    #ReportVideo_btn1{
        margin: 5vw 0 2vw 0;
    }
</style>
<script>
    import ARow from "ant-design-vue/es/grid/Row";
    import {mapState} from "vuex";
    export default {
        name: "ReportVideo",
        components: {ARow},
        computed:{
            ...mapState([
                'Loading'
            ])
        },
        data() {
            return {
                msg: 'hello vue',
                latitude:localStorage.getItem("latitude"),
                longitude:localStorage.getItem("longitude"),
                sid:localStorage.getItem("sid"),
                workModeId:localStorage.getItem("workModeId"),
                Authorization:localStorage.getItem("userToken"),
                reportHistory:localStorage.getItem("reportHistory")?JSON.parse(localStorage.getItem("reportHistory")):[],
                myVideoInfo:{ },
                isOk:"",
                createTime:"",
                progress:'',//上传文件的进度
                myFileName:'',//获取到的当前文件名
                path:'',//获取到的当前文件全路径
                file:'',//获取到的当前文件
                gis4_imei:localStorage.getItem("gis4_imei"),
                gis4_phone:localStorage.getItem("gis4_phone"),

            }
        },methods:{
            getVideo(){
                /*
                let me = this;
                //录制失败
                function onError(error) {
                    console.log('录制失败！错误码：' + error.code);
                    me.myVideoInfo.isOk = "0";
                    me.$store.commit('hideLoading'); //关闭遮罩
                }

                //录制成功
                function onSuccess(mediaFiles) {
                    me.$store.commit('showLoading'); //打开遮罩

                    /!*将该获取文件上传时间方法统一放入了上传方法中
                    let nowTime = new Date();
                    me.createTime = me.generateFileName(nowTime);*!/
                    me.file= mediaFiles[0];//得到json{}纯文件
                    me.path = me.file.fullPath;//得到本地的路径
                    me.myFileName = me.file.name;
                    console.log(me.file);
                    console.log("录制成功！"
                        + "文件名：" + me.myFileName
                        + "大小：" + me.file.size
                        + "localURL地址：" + me.file.localURL +
                        + "fullPath地址：" + me.file.fullPath);

                    //使用文件上传下载插件上传文件
                    me.uploadHandle(me.path);
                    //剩下的压缩注释和得到文件实体的方法移动到fromOnsuccess方法中
                }
                //开始录像（最长录制时间：15秒）onSuccess, onError, {duration: 15 codecs:'mp4',destinationFilename: "aaaaaaaa.3gp"
                navigator.device.capture.captureVideo(onSuccess, onError, {limit:1});
            */
                let me = this;
                console.log('我要拍摄视频');
                let success = function(result){
                    console.log("拍摄成功",result);

                    if (result.length > 0) {
                        me.$store.commit('showLoading'); //打开遮罩
                        //返回的数据一个为jsonArray，一个图片有未压缩地址filePath和压缩地址compressPath，循环得乘以2
                        for(let i = 0;i<(result.length)/2;i++){
                            me.path = result[2*i+1];//这里取压缩地址，未压缩地址为：result[2*i]
                            let arrName = result[2*i+1].split("/");
                            me.myFileName = arrName[(arrName.length) - 1];
                            //使用文件上传下载插件上传文件
                            me.getLocaltion(me.path);
                        }
                    }

                };
                let fail = function(error){
                    me.myVideoInfo.isOk = "0";
                    me.$store.commit('hideLoading'); //关闭遮罩
                    console.log("拍摄失败",error);
                };
                myMediaPlugin.takeVideo(success,fail,{});
            },
            /*fromOnsuccess(){
                /!*function videoTranscodeSuccess(result){
                        // result is the path to the transcoded video on the device
                        console.log('videoTranscodeSuccess, result: ' );
                        console.log(result );

                    };
                    function videoTranscodeError(err) {
                        console.log('videoTranscodeError, err: ' );
                        console.log(err);
                        me.myVideoInfo.isOk = "0";
                        me.$store.commit('hideLoading'); //关闭遮罩
                    }

                    VideoEditor.transcodeVideo(
                        videoTranscodeSuccess,
                        videoTranscodeError,
                         {
                            fileUri: path,// the fullPath to the video on the device
                            outputFileName: myFileName,// the file name for the transcoded video
                            outputFileType: VideoEditorOptions.OutputFileType.MPEG4,// android is always mp4
                            optimizeForNetworkUse: VideoEditorOptions.OptimizeForNetworkUse.YES,// ios only
                            saveToLibrary: true,// optional, defaults to true
                            maintainAspectRatio: true,
                            width: 640,
                            height: 640,
                            videoBitrate: 1000000, //1 megabit| optional, bitrate in bits, defaults to 1 megabit (1000000)
                            audioChannels: 2,
                            audioSampleRate: 44100,
                            audioBitrate: 128000, // 128 kilobits
                            fps: 24, // optional (android only), defaults to 24
                            progress: function(info) { // info will be a number from 0 to 100
                                console.log('transcodeVideo progress callback, info: ' + info);
                            }
                         }
                    );*!/
                //文件上传服务---------调用中
                /!*fileUpload(path);
                function fileUpload(fileURL) {
                    console.log('-------------文件上传服务---------调用中');
                    console.log('fileURL', fileURL)
                    return new Promise(async (resolve, reject) => {
                        let param = new FormData();
                        let fileEntry = await asyncResolveLocalFileSystemURL(fileURL);
                        let file = await asyncFileEntry(fileEntry);
                        let imgBlob = await asyncFileReader(file);
                        console.log(imgBlob);
                        param.append('file', imgBlob, myFileName);
                        param.append('longitude',me.longitude);
                        param.append('latitude',me.latitude);
                        param.append('userId',me.sid);
                        param.append('workModeId',me.workModeId);
                        param.append('time',me.createTime);
                        let config = {
                            headers: {
                                'Content-Type': 'multipart/form-data',
                                "Authorization":me.Authorization,
                            },
                        } // 添加请求头
                        axios.post('http://app.gis4.tdzcsoft.com:7000/app/work/upload',param, config).then(res=>{
                            if(res.status === 200){
                                me.myVideoInfo.fileName = myFileName;
                                me.myVideoInfo.createTime = me.createTime;
                                me.myVideoInfo.isOk = "1";
                                me.myVideoInfo.sid = me.sid;
                                me.reportHistory.unshift(me.myVideoInfo);
                                localStorage.setItem("reportHistory",JSON.stringify(me.reportHistory));//保存进内存
                                me.$store.commit('hideLoading');
                                me.isOk = "1";
                            }
                        }).catch((error) =>{
                            console.log("视频信息提交失败");
                            console.log(error);
                            me.myVideoInfo.fileName = myFileName;
                            me.myVideoInfo.createTime = me.createTime;
                            me.myVideoInfo.isOk = "0";
                            me.myVideoInfo.sid = me.sid;
                            me.reportHistory.unshift(me.myVideoInfo);
                            localStorage.setItem("reportHistory",JSON.stringify(me.reportHistory));//保存进内存
                            me.$store.commit('hideLoading');
                            me.isOk = "0";
                        })
                    })
                }*!/

                /!*!//以下是最初使用formdata上传文件的方式，通过path得到文件实体。现改为调用图片选择器插件得到MP4，压缩插件，上传插件
                function asyncResolveLocalFileSystemURL(fileURL) {
                    return new Promise((resolve, reject) => {
                        window.resolveLocalFileSystemURL(fileURL, fileEntry => {
                            resolve(fileEntry)
                        })
                    }, e => {
                        resolve(e)
                    }, e => {
                        reject(e)
                    })
                }

                function asyncFileEntry(fileEntry) {
                    return new Promise((resolve, reject) => {
                        fileEntry.file(function (file) {
                            resolve(file)
                        }, function (e) {
                            reject(e)
                        });
                    })
                }

                function asyncFileReader(file, type = "video/mp4") {//改动原3gp
                    return new Promise((resolve, reject) => {
                        try {
                            let reader = new FileReader();
                            reader.onloadend = function (e) {
                                let imgBlob = new Blob([this.result], {
                                    type
                                });
                                resolve(imgBlob)
                            };
                            reader.readAsArrayBuffer(file);
                        } catch (err) {
                            reject(err)
                        }
                    })
                }*!/
            },
            */

            //新方法多媒体选择器拍摄视频输出MP4，压缩文件，上传文件
            /*takeNewVideo(){
                //this.clickButton();
                let me = this;
                //文件压缩成功
                let videoTranscodeSuccess =  function(result){
                    // result is the path to the transcoded video on the device
                    console.log('videoTranscodeSuccess, result: ',result);

                };
                //文件压缩失败
                let videoTranscodeError = function(err) {
                    console.log('videoTranscodeError, err: ',err );
                    me.myVideoInfo.isOk = "0";
                    me.$store.commit('hideLoading'); //关闭遮罩
                };

                //录制失败
                let onError =  function(error) {
                    console.log('录制失败：' + error);
                    me.myVideoInfo.isOk = "0";
                    me.$store.commit('hideLoading'); //关闭遮罩
                }

                //录制成功
                let onSuccess = function(result) {
                    //me.$store.commit('showLoading'); //打开遮罩
                    console.log(result);

                    //let path = ("file://"+result[0]).toString();
                    //let path1 ="file:///"+result[i];
                    let path="file:///storage/emulated/0/Mob/PictureSelector_20190703_231247.mp4";
                    let nowTime = new Date();
                    let myFileName = me.getFileTime(nowTime)+".mp4";
                    console.log(path);

                    //使用文件上传下载插件上传文件
                    //me.uploadHandle(path);
                        VideoEditor.transcodeVideo(videoTranscodeSuccess, videoTranscodeError,
                            {
                                fileUri: path,// the fullPath to the video on the device
                                outputFileName: 'mytest02',// the file name for the transcoded video
                                outputFileType: VideoEditorOptions.OutputFileType.MPEG4,// android is always mp4
                                optimizeForNetworkUse: VideoEditorOptions.OptimizeForNetworkUse.YES,// ios only
                                saveToLibrary: true,// optional, defaults to true
                                maintainAspectRatio: true,
                                width: 640,
                                height: 640,
                                videoBitrate: 1000000, //1 megabit| optional, bitrate in bits, defaults to 1 megabit (1000000)
                                audioChannels: 2,
                                audioSampleRate: 44100,
                                audioBitrate: 128000, // 128 kilobits
                                fps: 24, // optional (android only), defaults to 24
                                progress: function(info) { // info will be a number from 0 to 100
                                    console.log('transcodeVideo progress callback, info: ' + info);
                                }
                            }
                        );


                };
                myMediaPlugin.takeVideo(onSuccess, onError, {massage:"随便写点"});

            },*/
            //得到文件命名，日期格式：2019-06-11 12:03:04
            generateFileName(date){
                return date.getFullYear().toString() +"-"+ complement(date.getMonth() + 1) +"-"+
                    complement(date.getDate()) +" "+ complement(date.getHours()) +":"+
                    complement(date.getMinutes()) +":"+ complement(date.getSeconds());
                function complement(n) {
                    return n < 10 ? '0' + n : n
                }
            },
            //得到文件命名2，格式：20190611120304
            getFileTime(date){
                //输出文件名
                let complement = function (n) {
                    return n < 10 ? '0' + n : n
                }

                return date.getFullYear().toString() + complement(date.getMonth() + 1) +
                    complement(date.getDate()) + complement(date.getHours()) +
                    complement(date.getMinutes()) + complement(date.getSeconds());

            },
                //绑定显示上传进度
             selectload(e){
                let me = this;
                if (e.lengthComputable) {
                    // this.sheetVisible=true;
                    let num=(e.loaded / e.total)*100;
                    me.progress = num.toFixed(2)+"%";
                    /*console.log('当前进度：' + e.loaded / e.total);0.97*/
                }
             },
            getLocaltion(fileURL) {
                let me = this;
                let nowTime = new Date();
                me.createTime = me.generateFileName(nowTime);
                baidumap_location.getCurrentPosition(result => {
                        console.log("上传文件调用经纬度:",result);
                        if(result.longitude===""||typeof (result.longitude)==="undefined"){
                            result.longitude = localStorage.getItem("longitude");
                            result.latitude = localStorage.getItem("latitude");
                        }
                        let params = {
                            LongitudeGcj02:result.longitude,
                            LatitudeGcj02:result.latitude,
                            userId:me.sid,
                            workModeId:me.workModeId,
                            time:me.createTime,
                        };
                        me.$store.commit("updateLatitude",result.latitude);
                        me.$store.commit("updateLongitude",result.longitude);
                        me.beginUpload(fileURL,params);
                    },error => {
                        console.log(error);
                        me.$store.commit('hideLoading');
                    //CoorType:"gcj02",OpenAutoNotifyMode:true,ScanSpan: 5000,LocationNotify:true
                },{CoorType:"gcj02",OpenAutoNotifyMode:true,Interval:5000,Distance:1,LocationNotify: true});
            },
            beginUpload (fileURL,params) {
                let me = this;
                //上传成功的回调方法
                let win = function(r) {
                    console.log(r);
                    /*console.log("Code = " + r.responseCode);
                    console.log("Sent = " + r.bytesSent);*/
                    console.log("Response = " + r.response);

                    //将上传信息放入本地上传历史资料信息显示
                    me.$store.commit('hideLoading');
                    me.isOk = "1";
                    me.myVideoInfo.fileName = me.myFileName;
                    me.myVideoInfo.createTime = me.createTime;
                    me.myVideoInfo.sid = me.sid;
                    me.myVideoInfo.isOk = "1";
                    me.reportHistory.push(me.myVideoInfo);
                    localStorage.setItem("reportHistory",JSON.stringify(me.reportHistory));//保存进内存
                };
                //上传失败的回调方法
                let fail = function(error) {
                    console.log("视频拍摄上传失败");
                    console.log(error);
                    /*console.log("An error has occurred: Code = " + error.code);
                    console.log("upload error source " + error.source);
                    console.log("upload error target " + error.target);*/
                    me.$store.commit('hideLoading');
                    me.isOk = "0";
                    me.myVideoInfo.fileName = me.myFileName;
                    me.myVideoInfo.createTime = me.createTime;
                    me.myVideoInfo.isOk = "0";
                    me.myVideoInfo.sid = me.sid;
                    me.reportHistory.push(me.myVideoInfo);
                    localStorage.setItem("reportHistory",JSON.stringify(me.reportHistory));//保存进内存
                };
                //上传参数
                let options = new FileUploadOptions();
                options.fileKey = 'file';
                options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
                options.mimeType = "video/3gpp";
                let headers = {
                    /*"Content-Type":'multipart/form-data'*/
                    "Authorization":me.Authorization,
                    "WorkPlanNo":me.$store.state.planNo,
                    "gis4_longitude":localStorage.getItem("longitude"),
                    "gis4_latitude": localStorage.getItem('latitude'),
                    "gis4_imei" : localStorage.getItem('gis4_imei'),
                    "gis4_phone" : localStorage.getItem('gis4_phone'),
                    "version" : localStorage.getItem('version'),
                    "gis4_workmode" :localStorage.getItem('workModeId'),
                    "gis4_time":new Date().getTime()

                };
                options.headers = headers;
                options.params = params;
                //实例化上传类
                let ft = new FileTransfer();
                //绑定上传进度函数
                ft.onprogress = me.selectload;
                //开始上传 上传插件方法调用
                ft.upload(fileURL, encodeURI('http://'+localStorage.getItem("apiHost")+'/app/work/upload'), win, fail,options);

            },

            //本地视频选择
            chooseVideo(){
                /*let me = this;
                let resultMedias=[];
                let args = {
                    'selectMode': 102, //100=image , 101=picker image and video , 102=video
                    'maxSelectCount': 1, //default 40 (Optional)
                    'maxSelectSize': 188743680, //188743680=180M (Optional) only android
                };

                let pickerOk = function(medias){
                    //medias [{mediaType: "image", path:'/storage/emulated/0/DCIM/Camera/2017.jpg', uri:"android retrun uri,ios retrun URL" size: 21993}]
                    resultMedias = medias;
                    console.log(resultMedias);
                    if(resultMedias.length>0){
                        me.$store.commit('showLoading'); //打开遮罩
                    }
                    me.myFileName =resultMedias[0].name;//赋值data文件名称
                    me.uploadHandle(resultMedias[0].uri);
                    /!*me.getThumbnail(medias,imgs);返回创建缩略图*!/

                }
                let pickerFail = function (e){
                    me.$store.commit('hideLoading');//关闭遮罩
                    console.log("音视频选择失败");
                    console.log(e)
                }
                //调用Picker本地视频选择
                MediaPicker.getMedias(args,pickerOk, pickerFail);
                */
                let me = this;
                console.log('我要选择视频');
                let success = function(result){
                    console.log("选择成功",result);
                    if (result.length > 0) {
                        me.$store.commit('showLoading'); //打开遮罩
                        //返回的数据一个为jsonArray，一个图片有未压缩地址filePath和压缩地址compressPath，循环得乘以2
                        for(let i = 0;i<(result.length)/2;i++){
                            me.path = result[2*i+1];//这里取压缩地址，未压缩地址为：result[2*i]
                            let arrName = result[2*i+1].split("/");
                            me.myFileName = arrName[(arrName.length) - 1];
                            me.getLocaltion(result[2*i+1]);
                        }
                    }
                };
                let fail = function(error){
                    console.log("返回选择结果失败");
                    console.log(error);
                };
                myMediaPlugin.selectVideo(success,fail,{});
            },
        }
    }
</script>

